import os
import json

def save_to_file(content, filename, directory="output"):
    """保存内容到文件
    
    Args:
        content: 要保存的内容
        filename: 文件名
        directory: 目录名，默认为"output"
    
    Returns:
        str: 保存的文件路径
    """
    # 确保目录存在
    if not os.path.exists(directory):
        os.makedirs(directory)
        
    # 构建完整的文件路径
    file_path = os.path.join(directory, filename)
    
    try:
        # 根据文件扩展名决定保存方式
        if filename.endswith(".json"):
            with open(file_path, "w", encoding="utf-8") as f:
                json.dump(content, f, ensure_ascii=False, indent=2)
        else:
            with open(file_path, "w", encoding="utf-8") as f:
                if isinstance(content, list):
                    f.write("\n".join(content))
                else:
                    f.write(content)
        
        return file_path
    except Exception as e:
        print(f"保存文件失败: {e}")
        return None

def load_from_file(filename, directory="output"):
    """从文件中加载内容
    
    Args:
        filename: 文件名
        directory: 目录名，默认为"output"
    
    Returns:
        加载的内容
    """
    # 构建完整的文件路径
    file_path = os.path.join(directory, filename)
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return None
    
    try:
        # 根据文件扩展名决定加载方式
        if filename.endswith(".json"):
            with open(file_path, "r", encoding="utf-8") as f:
                return json.load(f)
        else:
            with open(file_path, "r", encoding="utf-8") as f:
                return f.read()
    except Exception as e:
        print(f"加载文件失败: {e}")
        return None

def create_directory(directory):
    """创建目录
    
    Args:
        directory: 目录名
    
    Returns:
        bool: 是否创建成功
    """
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        return True
    except Exception as e:
        print(f"创建目录失败: {e}")
        return False

def list_files(directory="output"):
    """列出目录中的所有文件
    
    Args:
        directory: 目录名，默认为"output"
    
    Returns:
        list: 文件列表
    """
    if not os.path.exists(directory):
        return []
    
    try:
        return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    except Exception as e:
        print(f"列出文件失败: {e}")
        return []